import React, {PureComponent} from 'react';
import {connect} from 'dva';
import {Button, Form, Icon, Modal, Upload,} from 'antd';

@connect(({privateFileModel, loading}) => ({
  privateFileModel,
  loading: loading.models.privateFileModel,
}))
@Form.create()
class UploadFileForm extends PureComponent {
  state = {
    fileList: [],
    uploading: false,
  }
  doUpload = () => {
    const {dispatch, handleUpload, currentDir, groupId, uploadUrl,ftpId,} = this.props;
    const {fileList} = this.state;
    if (fileList && fileList.length > 5) {
      Modal.warning({title: "一次最多上传5个文件"});
      return;
    }

    // if (!this.checkUploadFileTypes()) {
    //   return;
    // }
    const formData = new FormData();
    fileList.forEach((file) => {
      formData.append('file', file);
    });
    formData.append('dirId', currentDir.id || 0);
    if (groupId) {
      formData.append('groupId', groupId);
    }if (ftpId) {
      formData.append('ftpId', ftpId);
    }
    this.setState({
      uploading: true,
    });
    // You can use any AJAX library you like


    let url = 'privateFileModel/uploadFiles';
    if (groupId) {
      url = 'privateFileModel/uploadFilesToGroup';
    }
    if (uploadUrl) {
      // 多次改动，目前就是上传外接文件 'privateFileModel/uploadOutsideFiles';
      url = uploadUrl;
    }
    dispatch({
      type: url,
      payload: formData,
      callback: (res) => {
        if (res.result == "ok") {
          this.setState({
            fileList: [],
            uploading: false,
          });
          Modal.success({title: res.msg});
          handleUpload();

        } else {

          this.setState({
            uploading: false,
          });
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });


  }


  checkUploadFileTypes = () => {
    const {fileList} = this.state;
    let result = true;
    fileList.forEach((file) => {
    });

    return result;
  }

  render() {
    const {modalVisible, form, handleUpload, handleModalVisible, supportUploadFileTypes, fileMaxUploadSize,ftpId,} = this.props;
    const {uploading, fileList} = this.state;
    let title = '上传文件';
    let accepts = "";
    if (supportUploadFileTypes) {
      let typeArray = supportUploadFileTypes.split(',');
      typeArray.forEach(item => {
        if (accepts) {
          accepts = accepts + ',.' + item;
        } else {
          accepts = '.' + item;
        }
      });
    }


    const props = {
      onRemove: (file) => {
        this.setState((state) => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: (file) => {
        const isLt2M = file.size / 1024 / 1024 < fileMaxUploadSize;
        if (!isLt2M) {
          Modal.warning({title: "上传文件大小超过限制"});
          return false;
        }

        this.setState(state => ({
          fileList: [...state.fileList, file],
        }));
        return false;
      },
      fileList,
      accept: accepts,
      multiple: true,
      // enctype:"multipart/form-data",
    };

    const okHandle = () => {
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        form.resetFields();
        handleUpload(fieldsValue);
      });
    };


    return (
      <Modal
        destroyOnClose
        maskClosable={false}
        title={title}
        visible={modalVisible}
        footer={null}
        onOk={okHandle}
        onCancel={() => handleModalVisible()}
      >
        <div>
          <Upload {...props}>
            <Button disabled={uploading}>
              <Icon type="upload"/> 选择文件
            </Button>
          </Upload>
          <Button
            type="primary"
            onClick={this.doUpload}
            disabled={fileList.length === 0}
            loading={uploading}
            style={{marginTop: 16, float: 'right'}}
          >
            {uploading ? '上传中' : '开始上传'}
          </Button>
          <p style={{clear: 'both', marginTop: '10px', lineHeight: 2, wordWwrap: 'break-word', wordBreak: 'break-all'}}>
            <span style={{color: '#ff6c00'}}>提示：</span><br/>
            1. 单个文件最大为{fileMaxUploadSize}M；<br/>
            {ftpId?null:"2. 目前仅支持zip,rar4以下，tar,tar.gz格式的压缩包扫描；"}<br/>

            {supportUploadFileTypes ? ('3. 可上传的文件类型： ' + supportUploadFileTypes) : null}

          </p>
        </div>
      </Modal>


    );
  }
}

export default UploadFileForm;
